//
//  RHHousesSearchViewController.swift
//  IMF
//
//  Created by 黄瑞东 on 2018/9/13.
//  Copyright © 2018年 imf. All rights reserved.
//

import UIKit
import URLNavigator
import SVProgressHUD
private let navigator: NavigatorType = RHRouterNavigator.sharedInstance.navigator

class RHHousesSearchViewController: RHViewController, UISearchBarDelegate, UITableViewDelegate, UITableViewDataSource, UITextFieldDelegate{
    
    var searchBar: UISearchBar?
    var searchBarView: UIView?
    var tableView: RHTableView?
    var cityName :String?
    var model = RHSearchAssociateResponseModel()
    var imageArray = Array<UIImage>()
    private let navigator: NavigatorType = RHRouterNavigator.sharedInstance.navigator
    
    override func viewDidLoad() {
        super.viewDidLoad()
        self.title = NSLocalizedString("HousesSearch", comment: "")
        
        self.navigationItem.leftBarButtonItem = UIBarButtonItem(image: UIImage(named: "nav_icon_back"), style: UIBarButtonItemStyle.plain, target: self, action: #selector(cancel))
        loadSearchBarView()
        loadTableView()
    }
    
    @objc func cancel() {
        self.dismiss(animated: false, completion: nil)
    }
    
    func loadSearchBarView() {
        self.searchBarView = UIView(frame: CGRect(x: 20, y: 7, width: UIScreen.main.bounds.width - 40, height: 40))
        self.searchBarView?.backgroundColor = .clear
        self.searchBarView?.layer.masksToBounds = true
        self.searchBarView?.layer.cornerRadius = 5
        self.searchBarView?.layer.borderColor = UIColor.clear.cgColor
        
        self.searchBar =  UISearchBar(frame: CGRect(x: 0, y: 0, width: self.searchBarView!.frame.width, height: self.searchBarView!.frame.height))
        self.searchBar?.barTintColor = UIColor.white
        self.searchBar?.tintColor = RHAppSkinColor.sharedInstance.secondaryTextColor;
        self.searchBar?.layer.borderColor = RHAppSkinColor.sharedInstance.placeholderTextColor.cgColor;
        self.searchBar?.layer.borderWidth = 1.0
        self.searchBar?.layer.cornerRadius = 5
        self.searchBar?.placeholder =  NSLocalizedString("SearchCity", comment: "")
        self.searchBar?.delegate = self
        
        self.searchBarView?.addSubview(self.searchBar!)
        self.view.addSubview(self.searchBarView!)
    }
    
    func searchBar(_ searchBar: UISearchBar, textDidChange searchText: String) {
        if searchText.count > 2 {
            SVProgressHUD.show()
            RHAPIManager.sharedInstance.doSearchAssociate(keyword: searchText, result: { [weak self] (msg, data) in
                guard let weakSelf = self else { return }
                SVProgressHUD.dismiss()
                weakSelf.model = data as! RHSearchAssociateResponseModel
                weakSelf.tableView?.reloadData()
            }) { (code, msg) in
                SVProgressHUD.dismiss()
            }
        }else{
            self.model.address = nil
            self.tableView?.reloadData()
        }
    }
    
    func loadTableView() {
        self.tableView = RHTableView(frame: CGRect.zero, style: .plain)
        self.tableView?.delegate = self;
        self.tableView?.dataSource = self;
        self.tableView?.register(RHImageTableViewCell.self, forCellReuseIdentifier: "RHImageTableViewCell")
        self.view.addSubview(self.tableView!)
        
        self.tableView?.snp.makeConstraints { [weak self](make) in
            guard let weakSelf = self else { return }
            make.top.equalTo(60)
            make.left.equalTo(weakSelf.view.snp.left)
            make.right.equalTo(weakSelf.view.snp.right)
            make.bottom.equalTo(weakSelf.view.snp.bottom)
        }
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if self.model.address == nil {
            return 0
        }
        return (self.model.address?.count)!
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        return 80
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        let cell: RHImageTableViewCell = tableView.dequeueReusableCell(withIdentifier: "RHImageTableViewCell", for: indexPath) as! RHImageTableViewCell
        cell.titleLabel?.text = ""
        cell.contentLabel?.text = self.model.address?[indexPath.row].address
        cell.leftImageView?.image = UIImage(named: "placeholder")

        if (imageArray.count) <= indexPath.row {
            if self.model.address?[indexPath.row].photo != nil{
                let url = URL(string: (self.model.address?[indexPath.row].photo)!)
                let request =  URLRequest(url: url!)
                let session  = URLSession.shared
                let dataTask =  session.dataTask(with: request, completionHandler: {
                    (data, response, taskError) -> Void in
                    if taskError != nil{
                        print(taskError.debugDescription)
                    }else{
                        DispatchQueue.main.async {
                            self.imageArray.append(UIImage(data: data!)!)
                            cell.leftImageView?.image = UIImage(data: data!)
                        }
                    }
                }) as URLSessionTask
                dataTask.resume()
            }else{
                self.imageArray.append(UIImage(named: "placeholder")!)
            }
        }else{
            cell.leftImageView?.image = imageArray[indexPath.row]
        }
        return cell
    }
    
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        let vc = RHHouseDetailsVC()
        vc.houseId = (self.model.address?[indexPath.row].houseId)!
        self.navigationController?.pushViewController(vc, animated: true)
    }
    
    func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
        view.endEditing(true)
    }
}
